package ynu.edu.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Where;
import ynu.edu.common.entity.LogicEntity;

import javax.persistence.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Entity
@Getter
@Setter
@Table(name = "orders")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Order extends LogicEntity {
    public static final  Integer ORDER_STATE_UNPAID = 0;
    public static final  Integer ORDER_STATE_PAID = 1;
    public static final  Integer ORDER_STATE_CONFIRMED = 2;
    public static final  Integer ORDER_STATE_REFUNDED = 3;
    @Column
    private Double orderTotal;

    @Column(insertable = false,
            nullable = false,
            columnDefinition="INT default 0")
    private Integer orderState; //订单状态（0：未支付； 1：已支付；2：已经确认；3：已退款）

    @ManyToOne(cascade = {CascadeType.MERGE},fetch = FetchType.EAGER)
    @JoinColumn(name = "shop_id")
    @JsonIgnoreProperties("orders")
    private Shop shop;

    @OneToMany(cascade = {CascadeType.MERGE,CascadeType.REMOVE,CascadeType.PERSIST},fetch = FetchType.EAGER)
    @JoinColumn(name = "order_id")
    @JsonIgnoreProperties("order")
    private Set<LineItem> lineItems;

    @ManyToOne(cascade = {CascadeType.MERGE},fetch = FetchType.EAGER)
    @JoinColumn(name = "customer_id")
    @JsonIgnoreProperties("orders")
    private Customer customer;

    @JsonIgnore
    public Order createOrder(Customer customer,Shop shop,List<LineItem> lineItems) {
        this.setShop(shop);
        this.setCustomer(customer);
        this.setLineItems(new HashSet<>(lineItems));
        this.setOrderTotal(lineItems.stream().mapToDouble(LineItem::getLineItemPrice).sum());
        this.setOrderState(ORDER_STATE_UNPAID);
        this.setIsDeleted(0);
        return this;
    }

    @JsonIgnore
    public Order updateOrder(List<LineItem> lineItemList) {
        this.lineItems.clear();
        this.setLineItems(new HashSet<>(lineItemList));
        this.setOrderTotal(lineItemList.stream().mapToDouble(LineItem::getLineItemPrice).sum());
        return this;
    }
}
